package dt.inlee.system.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import dt.inlee.common.constant.CommonConstant;
import dt.inlee.common.exception.FrameworkException;
import dt.inlee.common.util.BaseUtil;
import dt.inlee.common.util.SystemResourceUtil;
import dt.inlee.domain.SysMenu;
import dt.inlee.domain.SysUser;
import dt.inlee.system.dao.SysUserDao;
import dt.inlee.system.service.SysUserService;
import dt.inlee.system.vo.DictionaryBean;
import dt.inlee.system.vo.SysUserLoginBean;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @功能说明：处理单点登录Action
 * 
 * @添加时间：2012-4-25
 * @author 
 *
 */
@Scope("prototype")
@Results( { @Result(name = "success", location = "/index.jsp"),
		@Result(name = "input", location = "/login.jsp") })
@Controller("loginSSoAction")
public class LoginSSoAction extends ActionSupport {
	private static Logger logger = Logger.getLogger(LoginSSoAction.class);
	private static final long serialVersionUID = 5685121079327855527L;
	private HttpServletRequest request;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserDao sysUserDao;
	private SysUserLoginBean sysUserLoginBean = new SysUserLoginBean();
	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	/**
	 * @功能说明：处理ＣＡＳ跳转Action
	 * @return
	 * @throws Exception
	 */
	@Action(value = "loginSSo")
	public String loginSSo() throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest();
//		Object object = request.getSession().getAttribute(edu.yale.its.tp.cas.client.filter.CASFilter.CAS_FILTER_USER);
		AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
		String loginName = principal.getName();//获取用户名
	   	if (loginName != null) {
//			String loginName = (String) object;
	  		Map<String, SysUser> loginStatus;
	  		//此处忽略密码
			loginStatus = sysUserService.loginSSO(loginName);
	  		if (!BaseUtil.isEmpty(loginStatus)) {
	  			String status = loginStatus.keySet().iterator().next();
	    		SysUser sysUser = loginStatus.get(status);
				if (!sysUser.getDisabled()) {
					System.out.println("该用户已禁用,不能登录!");
					return "input";
				} else if ("startError".equalsIgnoreCase(status)) {
					System.out.println("生效开始日期大于当前日期,不能登录!");
					return "input";
				} else if ("endError".equalsIgnoreCase(status)) {
					System.out.println("生效结束日期小于当前日期,不能登录!");
					return "input";
				} else if ("betweenError".equalsIgnoreCase(status)) {
					System.out.println("生效日期已失效,不能登录!");
					return "input";
				}
    		
	    		int id = sysUser.getId();
	    		sysUserLoginBean.setId(id);
	    		sysUserLoginBean.setRealName(sysUser.getRealName());
				sysUserLoginBean.setMobileCode(sysUser.getMobile());
				
				List<SysMenu> sysMenus = sysUserDao.queryRightsMenusForSSO(sysUser.getId()+"");
				if (sysMenus == null || sysMenus.size() == 0) {
					System.out.println("该用户无任何权限,请授权后再登录!");
					return "input";
				}
//				sysUserLoginBean.setFlag(sysUser.getFlag());
				sysUserLoginBean.setRealName(sysUser.getRealName());
//				//获取机构信息
//				List<SysOrganization> sysOrgs = sysUserDao.querySysOrgsForSSO(sysUser.getId());
//				//设置机构信息
//				if (!BaseUtil.isEmpty(sysOrgs) && sysOrgs.size() > 0) {
//					sysUserLoginBean.setOrganizationId(sysOrgs.get(0).getId());
//					sysUserLoginBean.setOrganizationName(sysOrgs.get(0).getName());
//				}
				// 获取菜单
				sysUserLoginBean.setMenuList(sysMenus);
				// 登录人IP
				sysUserLoginBean.setIp(this.getRemortIP());
				sysUserLoginBean.setPassword(sysUser.getPassword());
				// 将登录信息放入session
				ActionContext.getContext().getSession().put(CommonConstant.SESSION_USER, sysUserLoginBean);
				// 将消费系统的链接地址放入session
				ActionContext.getContext().getSession().put("casConsumeURL", getCASConsumeURL());
				return SUCCESS;
  			}else{
  				System.out.println("该用户已失效,请授权后再登录!");
  				return "input";
  				
  			}
	   	}
		return null;
	}

	/**
	 * 获取消费系统的链接地址
	 * @return 
	 * @throws FrameworkException
	 */
	private String getCASConsumeURL() throws FrameworkException{
		List<DictionaryBean> urlList = SystemResourceUtil.getInstance().getResourceAsList("CASConsumeURL");
		String consumeURL = "";
		if (urlList != null && urlList.size() > 0) {
			logger.debug("LoginSSoAction getCASConsumeURL()");
			String url = urlList.get(0).getValue();
			if(!"".equals(url) &&  !"#".equals(url)){
				String name = urlList.get(0).getName();
				//消费地址
				consumeURL = "<span style='font-weight:bold; float:right;'><a href='" + url + "'>" + name + "</a></span>";
			}
		}
		return consumeURL;
	}
	
	/**
	 * @功能说明：获取登录用户IP
	 * @return
	 */
	private String getRemortIP() {
		if (ServletActionContext.getRequest().getHeader("x-forwarded-for") == null) {
			return ServletActionContext.getRequest().getRemoteAddr();
		}
		return ServletActionContext.getRequest().getHeader("x-forwarded-for");
	}

}
